# Static resource management blueprint

from flask import Blueprint, request, send_from_directory, jsonify
from flask_cors import CORS
import psycopg2.extras
import os
import logging

srm_blueprint = Blueprint('srm_blueprint', __name__)
CORS(srm_blueprint)  # 允许跨域请求

# 设置静态资源存储目录
BASE_UPLOAD_FOLDER = 'static/uploads'
if not os.path.exists(BASE_UPLOAD_FOLDER):
    os.makedirs(BASE_UPLOAD_FOLDER)

# 允许上传的文件类型
def allowed_file(filename):
    # csv文件后缀名
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ['csv', "zip", "png", "txt", "jpg", "pdf"]

def get_upload_folder(folder=None):
    """Get the full upload folder path, creating it if necessary"""
    if folder:
        upload_folder = os.path.join(BASE_UPLOAD_FOLDER, folder)
    else:
        upload_folder = BASE_UPLOAD_FOLDER
        
    if not os.path.exists(upload_folder):
        os.makedirs(upload_folder)
    return upload_folder

# 上传文件接口
@srm_blueprint.route('/upload', methods=['POST'])
def upload_file():
    # 获取文件夹参数，默认为None
    folder = request.form.get('folder', None)
    upload_folder = get_upload_folder(folder)

    if 'file' not in request.files:
        return jsonify({
            "status": -1,
            "errorCode": 1000,
            "errorMsg": "No file part",
            "resultBody": None
        })
    file = request.files['file']

    if file.filename == '':
        return jsonify({
            "status": -1,
            "errorCode": 1001,
            "errorMsg": "No selected file",
            "resultBody": None
        })
    
    if not file:
        return jsonify({
            "status": -1,
            "errorCode": 1004,
            "errorMsg": "File not found",
            "resultBody": None
        })
    
    elif not allowed_file(file.filename):
        return jsonify({
            "status": -1,
            "errorCode": 1005,
            "errorMsg": "File type not allowed",
            "resultBody": None
        })
    
    # 文档大小限制不超过1M
    elif file.content_length > 1024 * 1024:
        return jsonify({
            "status": -1,
            "errorCode": 1002,
            "errorMsg": "File size exceeds 1M",
            "resultBody": None
        })
    
    elif file.filename in os.listdir(upload_folder):
        return jsonify({
            "status": -1,
            "errorCode": 1003,
            "errorMsg": "File already exists",
            "resultBody": None
        })
    
    # 保存文件到指定目录
    filename = os.path.join(upload_folder, file.filename)
    try:
        file.seek(0)
        file.save(filename)
    except Exception as e:
        return jsonify({
            "status": -1,
            "errorCode": 1006,
            "errorMsg": f"Failed to save file: {e}",
            "resultBody": None
        })
    else:
        return jsonify({
            "status": 1,
            "errorCode": None,
            "errorMsg": None,
            "resultBody": filename
        })
    
    finally:
        file.close()

# 下载文件接口 - 修改为支持文件夹
@srm_blueprint.route('/download/<path:filepath>', methods=['GET'])
def download_file(filepath):
    # filepath格式可能是 "filename" 或 "folder/filename"
    full_path = os.path.join(BASE_UPLOAD_FOLDER, filepath)
    directory = os.path.dirname(full_path)
    filename = os.path.basename(full_path)
    
    if not os.path.exists(full_path):
        return jsonify({
            "status": -1,
            "errorCode": 1006,
            "errorMsg": "File not found",
            "resultBody": None
        })
    return send_from_directory(directory, filename, as_attachment=True)

# 删除文件接口 - 修改为支持文件夹
@srm_blueprint.route('/delete/<path:filepath>', methods=['DELETE'])
def delete_file(filepath):
    full_path = os.path.join(BASE_UPLOAD_FOLDER, filepath)
    if os.path.exists(full_path):
        os.remove(full_path)
        return jsonify({
            "status": 1,
            "errorCode": None,
            "errorMsg": None,
            "resultBody": "File deleted successfully"
        })
    else:
        return jsonify({
            "status": -1,
            "errorCode": 1000,
            "errorMsg": "File not found",
            "resultBody": None
        })

# 展示文件列表接口 - 修改为支持文件夹浏览
@srm_blueprint.route('/files', methods=['GET'])
@srm_blueprint.route('/files/<path:folder>', methods=['GET'])
def list_files(folder=None):
    target_folder = get_upload_folder(folder)
    
    # 获取相对于基础目录的路径
    rel_path = os.path.relpath(target_folder, BASE_UPLOAD_FOLDER)
    if rel_path == '.':
        rel_path = ''
    
    files = []
    dirs = []
    
    for item in os.listdir(target_folder):
        item_path = os.path.join(target_folder, item)
        if os.path.isfile(item_path):
            files.append({
                "name": item,
                "type": "file",
                "size": os.path.getsize(item_path),
                "ctime": os.path.getctime(item_path),
                "path": os.path.join(rel_path, item) if rel_path else item
            })
        elif os.path.isdir(item_path):
            dirs.append({
                "name": item,
                "type": "directory",
                "path": os.path.join(rel_path, item) if rel_path else item
            })
    
    # 合并文件和目录，目录在前
    items = dirs + files
    
    return jsonify({
        "status": 1,
        "errorCode": None,
        "errorMsg": None,
        "resultBody": {
            "current_folder": folder if folder else "root",
            "items": items
        }
    })